package com.devshephard.springcloud.config.customLoadBanlance;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class CustomLoadBanlanceImpl implements CustomLoadBanlance{

    AtomicInteger atomicInteger;

    public CustomLoadBanlanceImpl() {
        this.atomicInteger = new AtomicInteger(0);
    }

    @Override
    public Integer getServerIndex(List<ServiceInstance> instanceList) {

        int current;
        int next;

        do{
            current = this.atomicInteger.get();
            next = (current + 1) % instanceList.size();
        }while (!this.atomicInteger.compareAndSet(current,next));

        return next;
    }


}
